package com.itheima.advantagesup.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.advantagesup.dto.YddCateDTO;
import com.itheima.advantagesup.entity.YddCate;
import com.itheima.advantagesup.mapper.YddCateMapper;
import com.itheima.advantagesup.service.YddCateService;
import com.itheima.advantagesup.vo.CateVO;
import com.itheima.advantagesup.vo.YddCatePageBeanVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class YddCateServiceImpl implements YddCateService {
    @Autowired
    private YddCateMapper yddCateMapper;



    @Override
    public List<CateVO> all() {
        List<CateVO> list = yddCateMapper.all();
        return list;
    }

    @Override
    public YddCatePageBeanVO list(String catename, Integer page, Integer limit) {
        PageHelper.startPage(page,limit);
        List<YddCate>  c = yddCateMapper.list(catename);
        Page<YddCate> r1 = (Page<YddCate>) c;
        List<CateVO> cates = new Page<>();
        for (YddCate cate : c) {
            CateVO cateVO = yddCateToCateVO(cate);
            cates.add(cateVO);
        }
        Page<CateVO> r = (Page<CateVO>) cates;
        YddCatePageBeanVO yddCatePageBeanVO = new YddCatePageBeanVO(r1.getTotal(),r.getPages(),limit,1,r.getResult());
        return yddCatePageBeanVO;
    }

    @Override
    public void add(YddCateDTO yddCateDTO) {
        YddCate yddCate = yddCateDTOToYddCate(yddCateDTO);
        yddCateMapper.add(yddCate);
    }

    @Override
    public void delete(String id) {
        yddCateMapper.delete(id);
    }

    @Override
    public CateVO getCateById(String id) {
        YddCate yddCate = yddCateMapper.getCateById(id);
        CateVO cateVO = yddCateToCateVO(yddCate);
        return cateVO;
    }

    @Override
    public void update(YddCateDTO yddCateDTO) {
        YddCate yddCate = yddCateDTOToYddCate(yddCateDTO);
        yddCateMapper.update(yddCate);
    }

    /**
     * 把YddCate转化为YddCate
     * @param yddCateDTO
     * @return {@link YddCate}
     */
    private YddCate yddCateDTOToYddCate(YddCateDTO yddCateDTO) {
        YddCate yddCate = new YddCate();
        yddCate.setId(yddCateDTO.getId());
        yddCate.setCatename(yddCateDTO.getCatename());
        yddCate.setIcon(yddCateDTO.getIcon());
        yddCate.setSortNum(yddCateDTO.getSort_num());
        yddCate.setDefaultData(yddCateDTO.getDefault_data());
        return yddCate;

    }

    /**
     * YddCate转换为CateVO
     * @param cate
     * @return {@link CateVO}
     */
    private CateVO yddCateToCateVO(YddCate cate) {
        CateVO c = new CateVO();
        c.setId(cate.getId());
        c.setCatename(cate.getCatename());
        c.setIcon(cate.getIcon());
        c.setSort_num(cate.getSortNum());
        c.setDefault_data(cate.getDefaultData());
        return c;
    }
}
